import uuid
from django.contrib.auth.hashers import make_password
from django.core.cache import cache
from django.core.mail import send_mail
from rest_framework import viewsets, mixins
from rest_framework.decorators import action, api_view
from rest_framework.response import Response
from user.models import User, Address
from user.serializer import UserSerializer, UserLoginSerializer, UserRegisterSerializer, UserAddressSerializer
from utils.errors import ParamsException


class UserName(viewsets.GenericViewSet,
               mixins.ListModelMixin):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def list(self, request, *args, **kwargs):
        username = request.query_params['username']
        if User.objects.filter(username=request.query_params['username']).exists():
            res = {'data': {'count': 1000}}
            return Response(res)
        res = {'data': {'count': 0}}
        return Response(res)


class UserMobile(viewsets.GenericViewSet,
         mixins.ListModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def list(self, request, *args, **kwargs):
        mobile = request.query_params['mobile']
        if User.objects.filter(mobile=request.query_params['mobile']).exists():
            res = {'data': {'count': 100}}
            return Response(res)
        res = {'data': {'count': 0}}
        return Response(res)


class UserView(viewsets.GenericViewSet, mixins.RetrieveModelMixin,
               mixins.ListModelMixin):
    queryset = User.objects.all()

    """ 个人中心 """

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        user = User.objects.get(id=kwargs['pk'])
        email_active = user.email_active
        res = {'code': 200, 'data': {'id': user.id,
                                   'username': user.username,
                                   'mobile': user.mobile,
                                   'email': user.email,
                                   'email_active': email_active
                                   }}
        return Response(res)


    @action(detail=False,serializer_class=UserRegisterSerializer, methods=['POST'])
    def register(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        result = serializer.is_valid(raise_exception=False)
        if not result:
            res = {'code': 2336, 'msg': '字段校验失败'}
            raise ParamsException(res)
        password = make_password(request.data['password'])
        User.objects.create(username=request.data['username'],
                            password=password,
                            mobile=request.data['mobile'])
        token = uuid.uuid4()
        id = User.objects.filter(username=request.data['username']).first().id
        cache.set(token, id, timeout=30000)
        res = {
            'data': {'username': request.data['username'], 'id': id, 'token': token}}
        return Response(res)


    @action(detail=False, serializer_class=UserLoginSerializer, methods=['POST'])
    def login(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        result = serializer.is_valid(raise_exception=False)
        if not result:
            res = {'msg': '验证并没有通过哦', 'data': {'username': request.data['username'], 'password': request.data['password']}}
            raise ParamsException(res)
        user = User.objects.filter(username=request.data['username']).first()
        token = uuid.uuid4()
        cache.set(token, user.id, timeout=30000)
        res = {'code': 200, 'msg': '验证通过', 'data': {'token': token, 'user_id': user.id, 'username': user.username}}
        return Response(res)


    # 发送邮件
    @action(detail=False, methods=['PATCH'])
    def emails(self, request, *args, **kwargs):
        if User.objects.filter(email=request.data['email']).exists():
            res = {'msg': '邮箱存在不能再注册'}
            raise ParamsException(res)
        if User.objects.filter(email=request.data['email'], email_active=True).exists():
            res = {'msg': '邮箱存在不能再注册'}
            raise ParamsException(res)
        id = cache.get(request.data['token'])
        token = request.data['token']
        user = User.objects.filter(id=id).first()
        user.email = request.data['email']
        user.email_active = 1
        user.save()
        user = User.objects.filter(id=cache.get(request.data['token'])).first()
        message = user.generate_verify_email_url()
        send_mail('欢迎收到爸爸的邮件 ', message, 'wdhxm52@163.com', [request.data['email']])
        res = {'msg': '发送邮件成功'}
        return Response(res)


@api_view(['GET', 'POST'])
def address(request):

    if request.method == 'GET':

        """访问结束查询当前用户所有地址"""

        id = cache.get(request.query_params['token'])
        user = User.objects.filter(id=id).first()
        default_address_id = user.default_address_id
        addresses = Address.objects.filter(user=user).all()
        serializer = UserAddressSerializer(addresses, many=True)
        res = {'data': {
            'addresses': serializer.data,
            'default_address_id': default_address_id,
            'detial': '23333'
        }}
        return Response(res)


    if request.method == 'POST':

        """创建当前用户的地址"""

        id = cache.get(request.data['token'])
        user = User.objects.filter(id=id).first()
        if not id:
            res = {'msg': '登录超时'}
            raise ParamsException(res)
        address = Address.objects.create(user_id=id,
                               title=request.data['receiver'],
                               receiver=request.data['receiver'],
                               province_id=request.data['province_id'],
                               city_id=request.data['city_id'],
                               district_id=request.data['district_id'],
                               place=request.data['place'],
                               mobile=request.data['mobile'],
                               tel=request.data['tel'],
                               email=request.data['email']
                               )
        # address = Address.objects.filter(user_id=id).last()
        serializer = UserAddressSerializer(address)
        res = serializer.data
        return Response(res)


@api_view(['DELETE', 'PUT'])
def change_address(request, id):

    if request.method == 'PUT':

        """地址修改"""

        address = Address.objects.filter(id=request.data['id']).first()
        address.title = request.data['receiver']
        address.receiver = request.data['receiver']
        address.province_id = request.data['province_id']
        address.city_id = request.data['city_id']
        address.district_id = request.data['district_id']
        address.place = request.data['place']
        address.mobile = request.data['mobile']
        address.tel = request.data['tel']
        address.email = request.data['email']
        address.save()
        serializer = UserAddressSerializer(address)
        return Response(serializer.data)


    if request.method == 'DELETE':

        """ 地址删除 """

        address = Address.objects.filter(id=id).first()
        address.delete()
        res = {'msg': '删除成功'}
        return Response(res)


@api_view(['PUT'])
def change_title(request, id):

    """ 修改title """

    id = cache.get(request.data['token'])
    if not id:
        res = {'msg': '登录超时'}
        raise ParamsException(res)
    address = Address.objects.filter(id=request.parser_context['kwargs']['id']).first()
    address.title = request.data['title']
    address.receiver = request.data['title']
    address.save()

    return Response('2333')


@api_view(['PUT'])
def default_adress(request, id):

    """ 设置默认地址 """

    address = Address.objects.filter(id=id).first()
    user = User.objects.filter(id=address.user_id).first()
    user.default_address_id = id
    user.save()
    return Response('2333')
